$(document).ready(function () {
    var name = $('#name')
        , email = $('#email')
        , usecase = $('#usecase')
        , csrf = $('#csrf')
        , form = $('#form')
        , thankYou = $('#thank-you')
        , downloads = $('#downloads')
        , response
        , key;

    form.on('submit', function (event) {
        event.preventDefault();

        if (csrf.val() === '') {
            return false;
        }

        $.ajax('/', {
            method: 'POST',
            data: {
                name: name.val(),
                email: email.val(),
                usecase: usecase.val(),
                csrf: csrf.val()
            },
            beforeSend: function () {
                csrf.val('');
            },
            success: function (data, status, jqXHR) {
                thankYou.addClass('text-success');
                thankYou.text('Thank you for registering! Please check your email for details!');
            },
            error: function (jqXHR, status, error) {
                response = jQuery.parseJSON(jqXHR.responseText);
                console.log(response);

                if (response.message !== undefined) {
                    if (response.message  == "This email address already exists in our system.") {
                        thankYou.text("It looks like you already have an account with us. Forgot token? ");
                        var aTag = document.createElement('a');
                        aTag.setAttribute('href',"https://unwiredlabs.com/dashboard/forgot");
                        aTag.target = "_blank";
                        aTag.innerHTML = "Click here to retrieve it";
                        thankYou.append(aTag);
                        thankYou.append(".");
                    } else {
                        thankYou.addClass('text-danger');
                        thankYou.text(response.message);
                    }
                } else {
                    thankYou.addClass('text-danger');
                    thankYou.text('Ouch, something went wrong! Please refresh your the webpage and try again!');
                }

                if (response.csrf !== undefined) {
                    csrf.val(response.csrf);
                }
            },
            complete: function () {
                thankYou.removeClass('hidden');
            }
        });
    });

    usecase.change(function () {
        if ($(this).val() === "") {
            $(this).addClass("empty");
        } else {
            $(this).removeClass("empty");
        }
    });

});
